package com.example.juc.controller;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author jl
 * @since 2021/9/27 22:47
 */
public class WaitNotifyDemo {
    static Object lock = new Object();
    static Lock lock1 = new ReentrantLock();
    static Condition condition = lock1.newCondition();

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + " come in");
            LockSupport.park();
            LockSupport.park();
            System.out.println(Thread.currentThread().getName() + " 被唤醒");
        }, "t1");
        t1.start();
        new Thread(() -> {
            LockSupport.unpark(t1);
            LockSupport.unpark(t1);
            System.out.println(Thread.currentThread().getName() + " 发出唤醒通知");
        }, "t2").start();
    }

    private static void m2() {
        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lock1.lock();
            try {
                System.out.println(Thread.currentThread().getName() + " come in");
                condition.await();
                System.out.println(Thread.currentThread().getName() + " 被唤醒");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock1.unlock();
            }
        }, "t1").start();
        new Thread(() -> {
            lock1.lock();
            try {
                condition.signal();
                System.out.println(Thread.currentThread().getName() + " 发出唤醒通知");
            } finally {
                lock1.unlock();
            }
        }, "t2").start();
    }

    private static void m1() {
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + " come in");
            try {
                lock.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " 被唤醒");
        }, "t1").start();
        new Thread(() -> {
            lock.notifyAll();
            System.out.println(Thread.currentThread().getName() + " 发出唤醒通知");
        }, "t2").start();
    }
}
